<?php

namespace App\Http\Services;

use App\Models\Card;
use App\Models\Goods;
use App\Models\Order;
use App\Models\Shop;
use App\Models\Company;
use App\Utils\TianZhenLan;
use GuzzleHttp\Client;

class OrderService
{
    public static function notify_sip($orderId) {


    }

    /**
     * 预约成功通知
     * @param $orderId
     * @return mixed|\Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function notify_sip_book_status($orderId) {
        $order = Order::find($orderId);
        $data = [
            "venderOrderNo" => $order->sn,
            "sipOrderNo"    => $order->sip_sn,
            "userStatus"    => "1",
            "type"          => "0",
            "useTime"       => date('ymdHis'),
            "timestamp"     => (String)time()
        ];

        $jsonData   = json_encode($data);
        $deData     = RSAService::sip_public_encrypt($jsonData);
        $sign       = RSAService::tz_sign($jsonData);
        $sipConfig  = config('sip');
        $url        = $sipConfig['host'].$sipConfig['notify_url'];
        $client     = new Client();
        $res = $client->post($url, ['form_params' => ['data' => $deData, 'sign' => $sign]]);
        try {
            $res = json_decode($res->getBody()->getContents());
            $order->book_notify_count = 0;
        } catch (\Exception $e) {
            $order->book_notify_count -= 1;
        }
        $order->save();

        return $res;
    }

    /**
     * 使用结束通知
     * @param $orderId
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function notify_sip_use_status($orderId) {

        $order = Order::find($orderId);
        $data = [
            "venderOrderNo" => $order->sn,
            "sipOrderNo"    => $order->sip_sn,
            "userStatus"    => "1",
            "type"          => "1",
            "useTime"       => str_replace("-", "", $order->finish_at),
            "timestamp"     => (String)time()
        ];

        $jsonData   = json_encode($data);
        $deData     = RSAService::sip_public_encrypt($jsonData);
        $sign       = RSAService::tz_sign($jsonData);
        $sipConfig  = config('sip');
        $url        = $sipConfig['host'].$sipConfig['notify_url'];
        $client     = new Client();
        $res = $client->post($url, ['form_params' => ['data' => $deData, 'sign' => $sign]]);
        try {
            $res = json_decode($res->getBody()->getContents());
            $order->finish_notify_count = 0;
        } catch (\Exception $e) {
            $order->finish_notify_count -= 1;
        }
        $order->save();
    }

    static function send_book_success_mobile_message($orderId) {
        $order = Order::find($orderId);
        $company = Company::find($order->company);
        $goods = Goods::find($order->goods);
        $shop = Shop::find($order->shop);
        $mobile = $order->mobile;
        $companyName = $company->name;
        $goodsName = $goods->name;
        $codePass = $order->card;
        $shopName = $shop->name;
        return MobileMessageService::send_book_success($mobile, $companyName, $goodsName, $codePass, $shopName, $order->time);
    }

    static function submit_to_tzl($sn,  $shop, $time, $userName, $userMobile, $photoName, $photoMobile, $note = '', $adminNote = null) {
        $order      = Order::where('sn', $sn)->first();
        $oldShop    = $order->shop;
        $oldTime    = $order->time;
        $oldUserName    = $order->photoer_name;
        $oldUserMobile  = $order->photoer_mobile;
        $company        = $order->company;
        if ($userMobile != $order->mobile) {
            return ['code' => 203, 'msg' => '您的手机与下单时不一致'];
        }

        $data = [
            'shop'          => $shop,
            'time'          => $time,
            'user_name'     => $userName,
            'mobile'        => $userMobile,
            'status'        => Order::STATUS_BOOK_OK,   // 任意的修改都会造成状态被重置，管理员修改肯定不能这样
            'confirm_at'    => null,
            'update_count'  => $order->update_count + 1,
            'photoer_name'  => $photoName,
            'photoer_mobile'=> $photoMobile,
            'note'          => $note
        ];

        if ($adminNote !== null) {
            $data['kefu_note']     = $adminNote;
        }

        // 分配卡号
        if (!$order->company_card) {
            $shopInfo = Shop::find($shop);
            $goodsInfo = Goods::find($order->goods);
            $card = Card::get_valid_card($company, $order->city, $order->goods, $shopInfo->shop_code, $goodsInfo->gid, $time, $userMobile);
            if (!$card) {
                return ['code' => 202, 'msg' => '卡券不足，请尝试其他时间或联系客服'];
            }

            // 修改卡券状态
            $card->use_at = datetime();
            $card->order_id = $order->id;
            $card->save();
            $data['company_card']   = $card->code;
        }

        // DB::beginTransaction();
        $order->update($data);

        // 第三方 提交|修改 订单
        if ($company == Company::TZL) {
            // 向天真蓝提交订单
            if ($order->update_count == 1) {
                // 新增天真蓝预定

                $res = TianZhenLan::create_order($order->id);
                if (!$res) {
                    // 提交失败，恢复订单原始状态
                    Order::reset($order->id);
                    //Db::rollBack();
                    return ['code'=>203, 'msg'=>TianZhenLan::$error];
                }
            } else {
                // 修改天真蓝预定
                $res = TianZhenLan::update_order(
                    $order->id,
                    $oldShop, $data['shop'],
                    $oldTime, $data['time'],
                    $oldUserName, $data['photoer_name'],
                    $oldUserMobile, $data['photoer_mobile']
                );

                if (!$res) {
                    return ['code'=>203, 'msg'=>TianZhenLan::$error];
                }
            }
        }
        //DB::commit();

        // 发短信
        if ($company == Company::HMT) {
            // 海马体 发送预约提交成功短信
            // MobileMessageService::send_book_receive($order->mobile);

            // 通知后台管理员
        } else {
            // 天真蓝 发送预约成功短信
            // MobileMessageService::send_book_success($order->id);
        }

        return ['code'=>200, 'msg'=>'success'];
    }
}
